<script setup lang="ts">
  import { onMounted, ref } from 'vue'
  import { addPatientApi, patientDetailApi, updatePatientApi } from '@/apis/patient'
  import { onLoad } from '@dcloudio/uni-app'
  const formData = ref({
    name: '',
    idCard: '',
    gender: 1,
    defaultFlag: 1,
  })
  const id = ref('')
  const onSwitchChange = (event: any) => {
    formData.value.defaultFlag = event.detail.value ? 1 : 0
  }

  // 2. 表单验证规则
  const formRules = {
    name: {
      rules: [
        { required: true, errorMessage: '请填写患者姓名' },
        {
          pattern: /^[\u4e00-\u9fa5]{2,5}$/,
          errorMessage: '请输入中文姓名',
        },
      ],
    },
    idCard: {
      rules: [
        {
          required: true,
          errorMessage: '请填写身份证号',
        },
        {
          pattern:
            /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
          errorMessage: '请输入正确的身份证号',
        },
      ],
    },
  }

  // 3. 创建ref
  const formRef = ref<UniHelper.UniFormsInstance>()

  const isLoading = ref(false)

  const onSubmit = () => {
    formRef.value!.validate!((valid, errors) => {
      if (valid) {
        uni.showToast({
          title: '请检查表单',
          icon: 'error',
        })
        return
      }
      isLoading.value = true
      uni.showLoading({
        title: '提交中...',
      })

      if (id.value) {
        updatePatientApi({ ...formData.value, id: id.value }).then(async () => {
          uni.showToast({
            title: '编辑成功',
            icon: 'success',
          })
          id.value = ''
          // 返回上一页
          uni.navigateBack()
        })
        return
      }

      addPatientApi(formData.value)
        .then(async () => {
          uni.showToast({
            title: '添加成功',
            icon: 'success',
          })
          // 返回上一页
          uni.navigateBack()
        })
        .catch(() => {
          uni.showToast({
            title: '添加失败',
            icon: 'error',
          })
        })
        .finally(() => {
          isLoading.value = false
          uni.hideLoading()
        })
    })
  }

  // 启动时候钩子函数拿id
  onLoad(async (params) => {
    if (!params?.id) return
    uni.setNavigationBarTitle({ title: '编辑患者' })
    id.value = params?.id
    const res = await patientDetailApi(id.value)
    formData.value.defaultFlag = res.defaultFlag
    formData.value.gender = res.gender!
    formData.value.idCard = res.idCard!
    formData.value.name = res.name!
  })
</script>

<template>
  <scroll-page>
    <view class="archive-page">
      <uni-forms border label-width="220rpx" :model="formData" :rules="formRules" ref="formRef">
        <uni-forms-item label="患者姓名" name="name">
          <uni-easyinput
            v-model="formData.name"
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :input-border="false"
            :clearable="false"
            placeholder="请填写真实姓名"
          />
        </uni-forms-item>
        <uni-forms-item label="患者身份证号" name="idCard">
          <uni-easyinput
            v-model="formData.idCard"
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :style="{ color: '#121826' }"
            :input-border="false"
            :clearable="false"
            placeholder="请填写身份证号"
          />
        </uni-forms-item>
        <uni-forms-item label="患者性别" name="gender">
          <uni-data-checkbox
            v-model="formData.gender"
            selectedColor="#16C2A3"
            :localdata="[
              { text: '男', value: 1 },
              { text: '女', value: 0 },
            ]"
          />
        </uni-forms-item>
        <uni-forms-item label="默认就诊人" name="defaultFlag">
          <view class="uni-switch">
            <switch
              color="#20c6b2"
              :value="formData.defaultFlag === 1"
              @change="onSwitchChange"
              style="transform: scale(0.7)"
            />
          </view>
        </uni-forms-item>
        <button class="uni-button" @click="onSubmit">保存</button>
      </uni-forms>
    </view>
  </scroll-page>
</template>

<style lang="scss">
  @import './form.scss';
</style>
